package cn.gson.seventh.cotroller.user;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.gson.seventh.App;
import cn.gson.seventh.model.entity.User;
import cn.gson.seventh.service.SevenService;

/**
 * Servlet implementation class AddUser
 */
@WebServlet("/user/add")
public class AddUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private SevenService ss = App.getBean(SevenService.class);

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/jsp/user-form.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			request.setCharacterEncoding("utf-8");
			String userName = request.getParameter("userName");
			String gender = request.getParameter("gender");
			if (userName == null || userName.isEmpty()) {
				request.setAttribute("error", "用户名不能为空！");
				doGet(request, response);
				return;
			}
			User user = new User(userName, gender);
			if (ss.addUser(user)) {
				response.sendRedirect(request.getContextPath() + "/users");
			} else {
				request.setAttribute("error", "创建用户失败！");
				doGet(request, response);
			}
		} catch (Exception e) {
			request.setAttribute("error", e.getMessage());
			doGet(request, response);
		}
	}

}
